//
//  KLMGatewayWiFiViewController.swift
//  KLM
//
//  Created by 朱雨 on 2023/8/9.
//

import UIKit
import NetworkExtension

//typealias WiFiBlock = (_ name: String, _ password: String?) -> Void

class KLMGatewayWiFiViewController: UIViewController {
    
    @IBOutlet weak var SSIDField: UITextField!
    @IBOutlet weak var passField: UITextField!
    
    @IBOutlet weak var doneBtn: UIButton!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var selectwifiBtn: UIButton!
    
    @IBOutlet weak var WifiNameLab: UILabel!
    @IBOutlet weak var passwordLab: UILabel!
            
    var wifiBlock: WiFiBlock?
    
//    var isFromDeviceAdd = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private func setupUI() {
        
        if let result = KLMHomeManager.getWIFIMsg() {
            
            SSIDField.text = result.SSID
            passField.text = result.password
        } else {
            
            let ssid = KLMLocationManager.getCurrentWifiName()
            SSIDField.text = ssid
        }
        
        //弹出定位弹框
        KLMLocationManager.shared.getLocation {
            if KLMTool.isEmptyString(string: self.SSIDField.text) == nil {
                
                let ssid = KLMLocationManager.getCurrentWifiName()
                self.SSIDField.text = ssid
            }
        } failure: {
            
        }
        
        selectwifiBtn.backgroundColor = .lightGray.withAlphaComponent(0.1)
        selectwifiBtn.layer.cornerRadius = selectwifiBtn.height/2
        selectwifiBtn.setTitleColor(appMainThemeColor, for: .normal)
        doneBtn.layer.cornerRadius = doneBtn.height / 2
        doneBtn.backgroundColor = appMainThemeColor
        
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        
        WifiNameLab.text = KLMLocalizable.LANGLOC("Wi-Fi")
        SSIDField.placeholder = KLMLocalizable.LANGLOC("Please enter the Wi-Fi")
        selectwifiBtn.setTitle(KLMLocalizable.LANGLOC("Select Wi-Fi networks"), for: .normal)
        passwordLab.text = KLMLocalizable.LANGLOC("Password")
        passField.placeholder = KLMLocalizable.LANGLOC("Please enter the password")
        doneBtn.setTitle(KLMLocalizable.LANGLOC("Done"), for: .normal)
        
    }
    
    @IBAction func selectWifi(_ sender: Any) {
        
        KLMLocationManager.shared.getLocation {
            
            //弹框
            let vc = KLMWifiSelectViewController()
            vc.modalPresentationStyle = .overCurrentContext
            vc.modalTransitionStyle = .crossDissolve
            vc.wifiBlock = {[weak self] model in
                guard let self = self else { return  }
                self.SSIDField.text = model.WiFiName
                self.passField.text = model.WiFiPass
                
            }
            self.present(vc, animated: true)
        } failure: {
            
        }
    }
    
    @objc func appWillEnterForeground(){
        KLMLog("周期 ---将进入前台通知")
        //获取WiFi
        if let ssid = KLMLocationManager.getCurrentWifiName() {
            self.SSIDField.text = ssid
            if let wifilist = KLMWiFiManager.getWifiLists(), let model = wifilist.first(where: {$0.WiFiName == ssid}) {
                self.passField.text = model.WiFiPass
            }
        }
    }
    
    @IBAction func done(_ sender: Any) {
        
        if KLMTool.isEmptyString(string: SSIDField.text) == nil {
            
            return
        }
        
        apply()
    }
    
    private func apply() {
        
        var hotspotConfig = NEHotspotConfiguration.init(ssid: SSIDField.text!)
        if KLMTool.isEmptyString(string: passField.text) != nil {
            hotspotConfig = NEHotspotConfiguration.init(ssid: SSIDField.text!, passphrase: passField.text!, isWEP: false)
        }
        SVProgressHUD.show()
        NEHotspotConfigurationManager.shared.apply(hotspotConfig) { error in
            KLMLog(error)
            SVProgressHUD.dismiss()
            if error == nil { //加入和无法加入都返回nil
                let ssid = KLMLocationManager.getCurrentWifiName()
                guard let ssid = ssid else {
                    SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Connection failedure"))
                    return
                }
                if ssid == self.SSIDField.text { //加入了WiFi
                    KLMLog("入网成功")
                    self.next()
                } else {
                    SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Connection failedure"))
                }
            } else {
                if let err = error as? NSError {
                    if err.code == NEHotspotConfigurationError.alreadyAssociated.rawValue { //当前连接的WiFi
                        KLMLog("是当前连接的WiFi")
                        self.next()
                    } else if err.code == NEHotspotConfigurationError.invalidWPAPassphrase.rawValue {
                        SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Password error"))
                    } else {
                        SVProgressHUD.showInfo(withStatus: err.localizedDescription)
                    }
                }
            }
        }
    }
    
    private func next() {
        
//        if isFromDeviceAdd == false {
//            sendWifi()
//            return
//        }
        if let wifi = wifiBlock {
            wifi(SSIDField.text!, passField.text)
        }
        navigationController?.popViewController(animated: true)
    }
    
//    private func sendWifi() {
//        
//        KLMSmartNode.sharedInstacnce.delegate = self
//        
//        SVProgressHUD.show(withStatus: KLMLocalizable.LANGLOC("Send the Wi-Fi information to the device"))
//        
//        var value = "010201"
//        if serverType == .Alibaba {
//            value = "010202"
//        }
//        let parame = parameModel(dp: .customerCountingPower, value: value)
//        KLMSmartNode.sharedInstacnce.sendMessage(parame, toNode: KLMHomeManager.currentNode, isCanInternet: false)
//        DispatchQueue.main.asyncAfter(deadline: 0.5) {
//            self.sendWIfiMesssage()
//        }
//    }
    
//    private func sendWIfiMesssage() {
//        
//        KLMLog("发送WiFi信息给设备")
//        
//        let urlSSID: String = SSIDField.text!
//        let urlPassword: String = passField.text ?? ""
//        
//        //打开 1
//        let power: [UInt8] = [UInt8(1)]
//        
//        //32
//        var urlSSIDBytes: [UInt8] = [UInt8](urlSSID.data(using: .utf8)!)
//        urlSSIDBytes = urlSSIDBytes + [UInt8].init(repeating: 0, count: 32 - urlSSIDBytes.count)
//        //32
//        var urlPasswordBytes: [UInt8] = [UInt8](urlPassword.data(using: .utf8)!)
//        urlPasswordBytes = urlPasswordBytes + [UInt8].init(repeating: 0, count: 32 - urlPasswordBytes.count)
//        
//        // 1, url  0, header
//        let index: [UInt8] = [UInt8(0)]
//        // header: 16  url: 2个64
//        var appType = [UInt8](tenantCode.data(using: .utf8)!)
//        appType = appType + [UInt8].init(repeating: 0, count: 16 - appType.count)
//        
//        let parameters = Data.init(bytes: (power + urlSSIDBytes + urlPasswordBytes + index + appType), count: (power + urlSSIDBytes + urlPasswordBytes + index + appType).count)
//        let allBytes: String = parameters.hex
//        let parame = parameModel(dp: .customerCounting, value: allBytes)
//        KLMSmartNode.sharedInstacnce.sendMessage(parame, toNode: KLMHomeManager.currentNode, isCanInternet: false)
//    }
}

extension KLMGatewayWiFiViewController: KLMSmartNodeDelegate {
    
    func smartNode(_ manager: KLMSmartNode, didReceiveVendorMessage message: responsParame?) {
        
        if message?.dp == .customerCounting, let power: Int = message?.value as? Int {
            
            if power == 0 { ///打开成功
                
                ///存储WiFi信息
                KLMHomeManager.cacheWIFIMsg(SSID: SSIDField.text, password: passField.text)
                let model = KLMWiFiModel.init(WiFiName: SSIDField.text, WiFiPass: passField.text)
                KLMWiFiManager.saveWiFiName(wifiModel: model)
                
                ///更新服务器WiFi开启状态
                SVProgressHUD.show()
                KLMService.updateDevice(uuid: KLMHomeManager.currentNode.nodeuuidString, wifiStatus: 1) { response in
                    SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                    DispatchQueue.main.asyncAfter(deadline: 0.5) {
                        self.navigationController?.popViewController(animated: true)
                    }
                } failure: { error in
                    SVProgressHUD.dismiss()
                    KLMHttpShowError(error)
                }
            } else { ///失败
                
                SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The light failed to connect to Wi-Fi. Maybe the Wi-Fi password is incorrect") + "\(power)")
            }
        }
    }
    
    func smartNode(_ manager: KLMSmartNode, didfailure error: MessageError?) {
        KLMShowError(error)
    }
}
